<template>
  <j-modal
    :title="title"
    :width="980"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="24" pull="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -10px"
              label="经销商名称">
              <a-input style="width: 123%" placeholder="请输入经销商名称" v-decorator="['name',validatorRules.name]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24" pull="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -10px"
              label="状态">
              <!--这里更换下数据字典-->
              <j-dict-select-tag v-decorator="[ 'status', validatorRules.status ]" placeholder="状态"
                                 :type="'radioButton'" :triggerChange="true" dictCode="store_status"/>
              <!--              <j-dict-select-tag v-decorator="[ 'status', validatorRules.status ]" placeholder="状态" :type="'radioButton'" :triggerChange="true" :options="jselectMultiple.options"/>-->
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="12">
            <a-form-item label="设置渠道" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                mode="multiple"
                style="width: 100%"
                placeholder="请选择渠道"
                optionFilterProp="children"
                v-model="selectChannel"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="(channelInfo,channelIndex) in channelList" :key="channelIndex.toString()"
                                 :value="channelInfo.id">
                  {{ channelInfo.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="所属销售">
              <a-select
                mode="default"
                :allowClear="true"
                style="width: 100%"
                v-model="selectUser"
              >
                <a-select-option v-for="u in userList" :key="u.nameAndId">{{ u.realname }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24" pull="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -10px;"
              label="* 经销商所在地">
              <a-cascader style="width: 123%" :options="areaData" :value="areaValue" @change="onChange"
                          placeholder="Please select"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24" pull="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -10px"
              label="详细地址">
              <a-input style="width: 123%" placeholder="请输入详细地址" v-decorator="['address', validatorRules.address]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -10px"
              label="距离">
              <a-input style=" margin-right: 10px; width: 90% " placeholder="请输入距离"
                       v-decorator="['distance', validatorRules.distance]"/>km
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-right: -35px"
              label="联系人">
              <a-input placeholder="请输入联系人" v-decorator="['linkName', validatorRules.linkName]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系电话">
              <a-input placeholder="请输入联系电话" v-decorator="['phone', validatorRules.phone]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="联系电话2">
              <a-input placeholder="请输入联系电话2" v-decorator="['phone2', validatorRules.phone2]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24" pull="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -10px"
              label="简介">
              <a-input style="width: 123%" placeholder="请输入简介" v-decorator="['intro', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="24" pull="2">
            <a-form-item label="营业执照" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-left: -10px">
              <a-upload
                :showUploadList="false"
                :action="uploadAction"
                :data="{'isup':1,'dir':'channel/certificate'}"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="handleChange"
              >
                <a-button type="primary">上传</a-button>
              </a-upload>
              <ul class="select-div">
                <li :key="index" v-for="(file, index) in certificateList">
                  <a :href="file.url" target="_blank">{{ file.name }}</a> <a style="padding-left: 10px" href="#"
                                                                             @click="deleteFile(index)">删除</a>
                </li>
              </ul>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="24" pull="2">
            <a-form-item label="客户信息确认书" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-left: -10px">
              <a-upload
                :showUploadList="false"
                :action="uploadAction"
                :data="{'isup':1,'dir':'channel/certificate'}"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="handleInstructionChange"
              >
                <a-button type="primary">上传</a-button>
              </a-upload>
              <ul class="select-div">
                <li :key="index" v-for="(file, index) in instructionList">
                  <a :href="file.url" target="_blank">{{ file.name }}</a> <a style="padding-left: 10px" href="#"
                                                                             @click="deleteInstruction(index)">删除</a>
                </li>
              </ul>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :hidden="hiding"
              style="margin-right: -35px"
              label="门店图片">
              <a-input placeholder="请输入门店图片" v-decorator="['entityPicture', {}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :hidden="hiding"
              label="外部编码">
              <a-input placeholder="请输入外部编码" v-decorator="['extCode', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :hidden="hiding"
              style="margin-right: -35px"
              label="饿了么编码">
              <a-input placeholder="请输入饿了么编码" v-decorator="['elemeCode', {}]"/>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import {httpAction, getAction, postAction} from '@/api/manage'
import {ACCESS_TOKEN} from "@/store/mutation-types"
import pick from 'lodash.pick'
import moment from 'moment'
import JDictSelectTag from '../../../components/dict/JDictSelectTag'
import Vue from 'vue'
import StmReplenishmentModal from "./StmReplenishmentModal";
import StmRequiregoodsModal from "./StmRequiregoodsModal";
import StmReplenishmentExecModal from "./StmReplenishmentExecModal";
import StmReplenishmentItemModal from "./StmReplenishmentItemModal";
import StmRequiregoodsItemList from "../StmRequiregoodsItemList";
import StmReplenishmentPrintModal from "./StmReplenishmentPrintModal";

export default {
  name: 'StmStoreInfoModal',
  components: {JDictSelectTag},
  data() {
    return {
      jselectMultiple: {
        options: [
          {text: '维护中', value: '1'},
          {text: '合作中', value: '2'},
          {text: '已停用', value: '3'},
        ],
        value: 'Integer,Boolean'
      },
      title: '操作',
      visible: false,
      model: {},
      selectChannel: [],
      channelList: [],
      selectUser: [],
      userList: [],
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      labelCol1: {
        xs: {span: 24},
        sm: {span: 8}
      },
      wrapperCol1: {
        xs: {span: 24},
        sm: {span: 12}
      },
      areaData: [],
      areaValue: [],
      confirmLoading: false,
      uploadLoading: false,
      uploadLogoLoading: false,
      editEnable: true,
      hiding: true,
      headers: {},
      form: this.$form.createForm(this),
      pictureUrl: "",
      certificateList: [],
      instructionList: [],
      storeQrCodeUrl: "",
      logoUrl: "",
      validatorRules: {
        partnerId: {rules: [{required: true, message: '请输入商家id!'}]},
        name: {rules: [{required: true, message: '请输入经销商名称!'}]},
        phone: {rules: [{required: true, message: '请输入联系电话!'}]},
        phone2: {rules: [{required: true, message: '请输入联系电话2!'}]},
        address: {rules: [{required: true, message: '请输入详细地址!'}]},
        location: {rules: [{required: true, message: '请输入经销商所在地!'}]},
        distance: {rules: [{required: true, message: '请输入距离!'}]},
        linkName: {rules: [{required: true, message: '请输入联系人!'}]},
        storeId: {rules: [{required: true, message: '请输入门店编号!'}]},
        status: {rules: [{required: true, message: '请输入0-已关闭  9全面开放!'}]},
        sapAddressCode: {rules: [{required: true, message: '请输入SAP系统的库位编号'}]},
        sale: {rules: [{required: true, message: '请选择所属销售!'}]}
      },
      url: {
        add: '/stm/stmStoreInfo/add',
        edit: '/stm/stmStoreInfo/edit',
        getChannel: '/stm/stmChannelInfo/getChannelList',
        userList: '/sys/user/list',
        areaJson: '/data/area',
        fileUpload: window._CONFIG['domianURL'] + "/sys/common/ossUpload",
        imgerver: window._CONFIG['domianURL'] + "/sys/common/view",
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token": token};
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload;
    }
  },
  methods: {
    onCreateTimeChange: function (value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.createTime_begin = dateString[0]
      this.queryParam.createTime_end = dateString[1]
    },
    add() {
      this.pictureUrl = "";
      this.logoUrl = "";
      this.storeQrCodeUrl = "";
      this.edit({})
    },
    loadChannel(record) {
      let params = {};
      getAction(this.url.getChannel, params).then(res => {
        if (res.success) {
          this.channelList = res.result;

        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {

        this.selectChannel = record.selectChannelList;
      })
    },
    loadUserList(record) {
      let params = {};
      params.pageNo = 1;
      params.pageSize = 100;
      params.userType = 2;

      getAction(this.url.userList, params).then(res => {
        if (res.success) {
          this.userList = res.result.records;
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.selectUser = record.saleRealName;
      })
    },
    edit(record) {
      this.certificateList=[];
      this.instructionList=[];
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.editEnable = true;
      console.log(this.editEnable);
      this.loadChannel(record);
      this.getArea();
      this.loadUserList(record);
      this.visible = true
      this.pictureUrl = this.model.picture;
      this.logoUrl = this.model.logo;
      this.storeQrCodeUrl = this.model.storeQrCode;
      this.areaValue = [this.model.provinceCode, this.model.cityCode, this.model.districtCode, this.model.townCode]
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'storeId', 'name', 'sapAddressCode', 'status', 'address', 'dayTimeStart', 'dayTimeEnd', 'longitude', 'latitude', 'intro', 'phone', 'linkName', 'entityPicture', 'extCode', 'storeType', 'replenishmentDays', 'elemeCode', 'distance', 'phone2'))
        //时间格式化
        this.form.setFieldsValue({endTime: this.model.endTime ? moment(this.model.endTime) : null})
      })
      if(record!={} && record.certificateList.length>0){
        this.certificateList = eval(record.certificateList);
      }
      if(record!={} && record.instructionList.length>0){
        this.instructionList = eval(record.instructionList);
      }
    },
    beforeUpload: function (file) {
      var fileType = file.type;
      //TODO 验证文件大小
    },
    handleChange(info) {
      this.pictureUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if (response.success) {
          this.certificateList.push({name: response.result.fileName, url: response.result.url});
        } else {
          this.$message.warning(response.message);
        }
      }
    },
    handleInstructionChange(info) {
      this.pictureUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if (response.success) {
          this.instructionList.push({name: response.result.fileName, url: response.result.url});
        } else {
          this.$message.warning(response.message);
        }
      }
    },
    handleStoreQrChange(info) {
      this.storeQrCodeUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if (response.success) {
          this.model.storeQrCode = response.message;
          this.storeQrCodeUrl = this.model.storeQrCode;
        } else {
          this.$message.warning(response.message);
        }
      }
    },
    getPictureView() {
      if (this.model.picture !== null && this.model.picture !== undefined && this.model.picture !== '') {
        if ('http' === this.model.picture.substring(0, 4)) {
          return this.model.picture;
        }
        return this.url.imgerver + "/" + this.model.picture;
      }
    },
    handleLogoChange(info) {
      this.logoUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLogoLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLogoLoading = false;
        console.log(response);
        if (response.success) {
          this.model.logo = response.message;
          this.logoUrl = this.model.logo;
        } else {
          this.$message.warning(response.message);
        }
      }
    },
    getLogoView() {
      if (this.model.logo !== null && this.model.logo !== undefined && this.model.logo !== '') {
        if ('http' === this.model.logo.substring(0, 4)) {
          return this.model.logo;
        }
        return this.url.imgerver + "/" + this.model.logo;
      }
    },
    getStoreQrView() {
      if (this.model.storeQrCode !== null && this.model.storeQrCode !== undefined && this.model.storeQrCode !== '') {
        if ('http' === this.model.storeQrCode.substring(0, 4)) {
          return this.model.storeQrCode;
        }
        return this.url.imgerver + "/" + this.model.storeQrCode;
      }
    },
    close() {
      this.$emit('close')
      this.selectChannel = [];
      this.visible = false
    },
    getArea() {
      getAction(this.url.areaJson).then((res) => {
        this.areaData = res
      })
    },
    onChange(value, selectedOptions) {
      console.log(value, selectedOptions)
      this.model.provinceCode = selectedOptions[0].value
      this.model.cityCode = selectedOptions[1].value
      this.model.districtCode = selectedOptions[2].value
      this.model.townCode = selectedOptions[3].value
      this.model.province = selectedOptions[0].label
      this.model.city = selectedOptions[1].label
      this.model.district = selectedOptions[2].label
      this.model.town = selectedOptions[3].label
      this.areaValue = [this.model.provinceCode, this.model.cityCode, this.model.districtCode, this.model.townCode]
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          formData.certificateList = JSON.stringify(this.certificateList);
          formData.instructionList = JSON.stringify(this.instructionList);
          if(formData.certificateList=="[]" || formData.certificateList.length==0){
            that.$message.warning("请上传营业执照");
            that.confirmLoading = false
            return;
          }
          if(formData.instructionList=="[]" || formData.instructionList.length==0){
            that.$message.warning("请上传客户信息确认书");
            that.confirmLoading = false
            return;
          }
          //时间格式化
          formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD HH:mm:ss') : null;
          formData.brandCategory = 1;
          formData.channelIds = this.selectChannel.length > 0 ? this.selectChannel.join(",") : '';
          if (that.selectUser == null || that.selectUser.length == 0) {
            that.$message.success("请选择所属销售");
            that.confirmLoading = false
            return;
          }
          formData.saleUserId = that.selectUser.split("&:")[1];
          formData.saleRealName = that.selectUser.split("&:")[0];
          if (formData.districtCode == null || formData.districtCode == undefined) {
            that.$message.success("请输入经销商所在地");
            that.confirmLoading = false
            return;
          }
          console.log(formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })


        }
      })
    },
    handleCancel() {
      this.close()
    },
    saleChange(option) {
      console.log(111)
      let i = 0;
    },
    groupChange(option) {

      let i = 0;
    },
    deleteFile(index) {
      this.certificateList.splice(index, 1);
    },
    deleteInstruction(index){
      this.instructionList.splice(index, 1);
    }
  }
}
</script>

<style lang="less" scoped>

</style>
